import random
import traceback
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.forms import model_to_dict
from django.http import HttpResponse, HttpResponseNotFound
from django.views.decorators.http import require_http_methods
from django.utils import timezone
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework import generics, mixins, views, permissions
from django.template import Context, loader

from fast_mail.models import Truck, Driver, MailRecord
from fast_mail.fast_mail_serializers import DriverSerializer, MailRecordSerializer, TruckSerializer
from common.permission_utils import CustomerPermission

from my_celery.tasks import send_mail


class AddFastMail(APIView):
    """
    添加快递信息
    """

    # permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        data = request.data
        name = data.get('name')
        to_place = data.get('to_place')
        from_place = data.get('from_place')
        sender = data.get('sender')
        receiver = data.get('receiver')
        description = data.get('description')
        receiver_phone = data.get('receiver_phone')
        sender_phone = data.get('sender_phone')
        if not all([name, to_place, from_place, sender, receiver, description, receiver_phone, sender_phone]):
            return Response({'code': 405, 'message': '信息不全'})
        try:
            order_id = create_order_id(request.user.id)
            mail_record = MailRecord.objects.create(order_id=order_id)
            mail_record.name = name
            mail_record.to_place = to_place
            mail_record.from_place = from_place
            mail_record.sender = sender
            mail_record.receiver = receiver
            mail_record.desc = description
            mail_record.receiver_phone = receiver_phone
            mail_record.sender_phone = sender_phone
            mail_record.save()
            subject = '快递发送通知'
            context = {}
            from_email = '491061108@qq.com'  # 邮件发送人
            recipient_list = ['2837379503@qq.com', '18332782513@163.com']  # 邮件接收人

            email_template_name = 'template.html'
            t = loader.get_template(email_template_name)  # 导入模板

            html_content = t.render(context)  # 模板参数
            send_mail.delay(subject, html_content, from_email, recipient_list)
            return Response({'code': 200})
        except:
            error = traceback.format_exc()
            print('error', error)
            return Response({'code': 500, 'error': error})


class GetDriverList(APIView):
    """
    获取司机列表
    """
    serializer_class = DriverSerializer
    # permission_classes = [permissions.IsAdminUser, ]

    def get(self, request):
        data = request.query_params
        status = data.get('status', 'all')
        if status == 'all':
            driver = Driver.objects.all()
        else:
            driver = Driver.objects.filter(status=status)
        driver = DriverSerializer(driver, many=True)
        result = driver.data
        return Response({'code': 200, 'data': result})


class GetMail(APIView):
    """
    获取快递
    """
    serializer_class = MailRecordSerializer
    # permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        mail = MailRecord.objects.all()
        result = MailRecordSerializer(mail, many=True)
        return Response({'code': 200, 'data': result.data})


class GetTruckList(APIView):
    """
    获取卡车列表
    """
    serializer_class = TruckSerializer
    # permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        data = request.query_params
        status = data.get('status', 'all')
        if status == 'all':
            truck = Truck.objects.all()
        else:
            truck = Truck.objects.filter(status=status)
        truck = TruckSerializer(truck, many=True)
        result = truck.data
        return Response({'code': 200, 'data': result})


class GetUserMailList(APIView):
    """
    获取用户自己的快递列表
    """
    serializer_class = MailRecordSerializer
    permission_classes = [permissions.IsAuthenticated, CustomerPermission]

    def get(self, request):
        user_id = request.user.id
        mail_list = MailRecord.objects.filter(user_id=user_id)
        mail_list = MailRecordSerializer(mail_list, many=True)
        return Response({'code': 200, 'data': mail_list.data})
